import { memo, useEffect, useRef, useState } from 'react'

import NavBar from '../../../components/NavBar'

import { List, DatePicker, Drawer, Modal } from 'antd-mobile'

import styles from './index.module.scss'

import { useDispatch } from 'react-redux'

import EditInput from './components/EditInput'

import { getProfile, editProfile, editPhoto } from '../store/action'

import { useSelector } from 'react-redux'

import classNames from 'classnames'

import EditList from './components/EditList'

import { useHistory } from 'react-router'

import dayjs from 'dayjs'
import { removeItem } from '@/utils/storage'
import { logout } from '@/pages/Login/store/action'

export default memo(function ProfileEdit() {
  const [open, setOpen] = useState({
    visible: false,
    type: '',
    value: '',
  })

  const dispatch = useDispatch()

  const { photo, name, gender, birthday, intro } = useSelector(
    (state) => state.userReducer.profile
  )
  const formConfigMap = {
    name: {
      type: '昵称',
      visible: true,
      value: name,
    },
    intro: {
      type: '简介',
      visible: true,
      value: intro,
    },
  }

  const history = useHistory()

  useEffect(() => {
    dispatch(getProfile())
  }, [dispatch])

  const [listOpen, setListOpen] = useState({
    visible: false,
    typr: '',
  })

  const onclose = () => {
    setListOpen({
      visible: false,
      type: '',
    })
  }

  const config = {
    gender: [
      {
        title: '男',
        onClick() {
          onclose()
          dispatch(editProfile({ gender: 0 }))
        },
      },
      {
        title: '女',
        onClick() {
          onclose()
          dispatch(editProfile({ gender: 1 }))
        },
      },
    ],
    avatar: [
      {
        title: '拍照',
        onClick() {
          console.log('拍照')
        },
      },
      {
        title: '上传',
        onClick() {
          fileRef.current.click()
        },
      },
    ],
  }

  const updateAvatar = (e) => {
    const fd = new FormData()
    fd.append('photo', e.target.files[0])
    dispatch(editPhoto(fd))
    onclose()
  }

  const fileRef = useRef()

  const onDateChange = (date) => {
    dispatch(editProfile({ birthday: dayjs(date).format('YYYY-MM-DD') }))
    onclose()
  }

  const { replace } = useHistory()

  const loginOut = () => {
    Modal.alert('温馨提示', '你确定要退出吗？', [
      { text: '取消' },
      {
        text: '确定',
        onPress() {
          removeItem()
          dispatch(logout())
          replace('/login')
        },
      },
    ])
  }

  return (
    <div className={styles.root}>
      <NavBar onLeftClick={() => history.push('/home/profile')}>
        个人信息
      </NavBar>
      <div className="content">
        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              arrow="horizontal"
              extra={
                <span className="avatar-wrapper">
                  <img src={photo} alt="" />
                </span>
              }
              onClick={() => setListOpen({ visible: true, type: 'avatar' })}
            >
              头像
            </List.Item>
            <input type="file" hidden ref={fileRef} onChange={updateAvatar} />
            <List.Item
              arrow="horizontal"
              extra={name}
              onClick={() => setOpen(formConfigMap.name)}
            >
              昵称
            </List.Item>
            <List.Item
              arrow="horizontal"
              extra={
                <span
                  className={classNames('intro', intro ? 'normal' : '')}
                  onClick={() => setOpen(formConfigMap.intro)}
                >
                  {intro || '未填写'}
                </span>
              }
            >
              简介
            </List.Item>
          </List>

          <List className="profile-list">
            <List.Item
              extra={gender === 0 ? '男' : '女'}
              arrow="horizontal"
              onClick={() => setListOpen({ visible: true, type: 'gender' })}
            >
              性别
            </List.Item>
            <DatePicker
              mode="date"
              value={new Date(birthday)}
              title="选择生日"
              minDate={new Date('1950-01-01')}
              maxDate={new Date()}
              onChange={onDateChange}
            >
              <List.Item arrow="horizontal">生日</List.Item>
            </DatePicker>
          </List>
        </div>

        <div className="logout">
          <button className="btn" onClick={loginOut}>
            退出登录
          </button>
        </div>
      </div>
      <Drawer
        position="right"
        className="drawer"
        style={{
          minHeight: document.documentElement.clientHeight,
        }}
        children={''}
        open={open.visible}
        sidebar={
          open.visible && (
            <EditInput
              onClick={() => setOpen({ visible: false, type: '', value: '' })}
              onsubInfo={() => setOpen({ ...open, visible: false })}
              {...open}
            />
          )
        }
      />

      <Drawer
        position="bottom"
        className="drawer"
        children={''}
        sidebar={
          listOpen.visible && (
            <EditList config={config} type={listOpen.type} onclose={onclose} />
          )
        }
        open={listOpen.visible}
        onOpenChange={onclose}
      />
    </div>
  )
})
